<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

// 请求开始：启用输出缓冲，避免 BOM/无意输出破坏响应头设置
ob_start();

// PHP版本验证需要大于8.0.0
if (version_compare(PHP_VERSION, '8.0.0', '<')) {
    
    die('OneBase Require PHP > 8.0.0 !');
}

// 定义应用目录
define('APP_PATH', __DIR__ . '/../app/');

// 检测是否安装
$cfgFile = __DIR__ . '/../config/database.php';
$needInstall = false;
if (!is_file($cfgFile)) {
    $needInstall = true;
} else {
    $cfg = include $cfgFile;
    if (!is_array($cfg)) {
        $needInstall = true;
    } else {
        $default     = $cfg['default'] ?? 'mysql';
        $connections = $cfg['connections'] ?? [];
        $conn        = $connections[$default] ?? [];
        $dbName      = $conn['database'] ?? '';
        $hostname    = $conn['hostname'] ?? '';
        $username    = $conn['username'] ?? '';
        $sysKey      = $cfg['sys_data_key'] ?? 'OneBase';
        if ($dbName === '' || $hostname === '' || $username === '' || $sysKey === 'OneBase') {
            $needInstall = true;
        }
    }
}
if ($needInstall) {
    header("Location: /install.php", true, 302);
    exit;
}

// 切换为 TP8 引导方式
require __DIR__ . '/../vendor/autoload.php';

use think\App;

// 统一：先加载根级公共事件，确保 InitBase/InitHook 对所有应用生效
$app = new App();
if (is_file(__DIR__ . '/../app/event.php')) {
    $app->loadEvent(include __DIR__ . '/../app/event.php');
}

// 执行HTTP应用并响应（支持入口通过 BIND_MODULE 绑定具体应用）
$http = $app->http;

try {
    $response = (defined('BIND_MODULE') && is_string(BIND_MODULE) && BIND_MODULE !== '')
        ? $http->name(BIND_MODULE)->run()
        : $http->run();

    $response->send();
    $http->end(isset($response) ? $response : null);

    // 响应结束：释放输出缓冲，确保头部与 Set-Cookie 正常发送
    ob_end_flush();
} catch (\Throwable $e) {
    // 捕获并显示异常，便于定位 500 的具体原因
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Error: ' . $e->getMessage() . "\n";
    echo $e->getFile() . ':' . $e->getLine() . "\n";
    echo $e->getTraceAsString() . "\n";
} finally {
    $http->end(isset($response) ? $response : null);
    // 释放输出缓冲，确保头部与 Set-Cookie 正常发送
    ob_end_flush();
}